package com.jielihaofeng.netty.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.util.Scanner;

/**
 * @author Johnnie Wind
 * @description CloseFuture 的使用
 * @date 2021/11/9 17:06
 */
@Slf4j
public class CloseFutureClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup(2);
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                                ch.pipeline().addLast(new StringEncoder());
                            }
                        }
                )
                .connect("localhost", 8088);
        System.out.println(channelFuture.getClass());
        Channel channel = channelFuture.sync().channel();
        log.debug("{}",channel);

        // 输入线程
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                // 输入q退出
                if ("q".equals(line)){
                    // close方法也是异步操作，也许1s之后才真正关闭
                    channel.close();
                    // log.debug("处理关闭之后的操作"); // 不能在这里善后
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"input").start();

        // 获取CloseFuture对象
        ChannelFuture closeFuture = channel.closeFuture();
        log.debug("waiting close...");
        // 1. sync 同步处理关闭
        closeFuture.sync();
        log.debug("处理关闭之后的操作");
        System.out.println(closeFuture.getClass());

        // 2. listener 异步处理关闭
        closeFuture.addListener((ChannelFutureListener) future -> {
            log.debug("处理关闭之后的操作");
            // 优雅地停止group中的线程
            group.shutdownGracefully().addListener((GenericFutureListener)f->{
                log.debug("优雅结束group");
            });
        });
    }
}

// Netty 异步提升的是什么？
// 单位时间内处理任务的个数（吞吐量）

// 单线程没法提高效率，必须配合多线程和多CPU才能发挥异步优势
// 异步没有缩短响应时间，反而有所增加
// 合理进行任务的拆分